package com.itrh.org.service.impl;

import com.itrh.base.service.impl.BaseServiceImpl;
import com.itrh.org.query.DepartmentQuery;
import com.itrh.org.util.Result;
import com.itrh.org.domain.Department;
import com.itrh.org.mapper.DepartmentMapper;
import com.itrh.org.service.IDepartmentService;
import com.itrh.org.util.pageResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * ClassName: DepartmentServiceImpl
 *
 * @author XHU_WHY
 * @version V1.0
 * @since 2024/3/29 14:18
 */
@Service
public class IDepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {
    @Resource
    private DepartmentMapper departmentMapper;

    @Override
    @Transactional
    public Result saveOrUpdate(Department department) {
        try {
            if (department.getId() == null) {
                departmentMapper.insert(department);
                department.setCreateTime(LocalDateTime.now());
            }
            if (department.getParentId() == null) {
                department.setPath("/" + department.getId());
            } else {
                department.setPath(departmentMapper.selectById(department.getParentId()).getPath() + "/" + department.getId());
            }
            departmentMapper.update(department);
            return Result.success();
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("操作失败");
        }
    }

    @Override
    public Result getTree() {
        List<Department> departments = departmentMapper.getTree();
        return Result.success(departments);
    }

    @Override
    public Department selectByName(String name) {
        return departmentMapper.selectByName(name);
    }
}
